import React, { useState } from 'react';
import { Layout, Menu, Avatar, Dropdown, message } from 'antd';
import { Link, useLocation, useNavigate, Location, Outlet } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { logoutUser as logout } from '../store/userSlice';

interface LocationState {
  content?: React.ReactNode;
}

const { Header, Sider, Content } = Layout;

interface MenuItem {
  key: string;
  label: string;
  path: string;
}

const menuList: MenuItem[] = [
  { key: '1', label: '仪表盘', path: '/dashboard' },
  { key: 'blog-articles', label: '文章管理', path: '/blog/articles' },
];

const BasicLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const location = useLocation() as Location<LocationState>;
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const handleLogout = () => {
    dispatch(logout());
    navigate('/login');
    message.success('退出登录成功');
  };

  const userMenu = (
    <Menu>
      <Menu.Item key="profile">个人中心</Menu.Item>
      <Menu.Item key="setting">设置</Menu.Item>
      <Menu.Item key="logout" onClick={handleLogout}>退出登录</Menu.Item>
    </Menu>
  );

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div style={{ height: '64px', lineHeight: '64px', textAlign: 'center', color: '#fff', fontSize: '18px' }}>
          {collapsed ? '后台' : '博客管理系统'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuList.map(item => ({...item, label: <Link to={item.path}>{item.label}</Link>}))}
        />
      </Sider>
      <Layout>
        <Header style={{ background: '#fff', padding: 0, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
          <Dropdown overlay={userMenu} placement="bottomRight">
            <a style={{ marginRight: 24 }}>
              <Avatar /> 管理员
            </a>
          </Dropdown>
        </Header>
        <Outlet />
        <Content style={{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280 }}>
          {location.state?.content ?? null}
        </Content>
      </Layout>
    </Layout>
  );
};
export default BasicLayout;